# -*- coding: utf-8 -*-

# @Time   : 2021/12/14 5:13 下午
# @Author : 贾浩天
# @Email  : jiahaotian@rokedata.com
# @File   : roke_excel_import_wizard.py
# @Description: 导入逻辑后台

from odoo import models, fields, api, _, SUPERUSER_ID
from odoo.exceptions import UserError, ValidationError
import base64
import xlrd
import logging
_logger = logging.getLogger(__name__)


class RokeExcelImportWizard(models.TransientModel):
    _name = "roke.excel.import.config.wizard"
    _description = "数据导入"

    file = fields.Binary('文件')
    model_id = fields.Many2one('roke.excel.import.config', string='模型')

    def upload_document(self):
        # 数据列表
        data_list = []
        if not self.file:
            raise ValidationError('未上传要导入的文件！')
        # 组织导入模板字段
        _list = []
        for i in self.model_id.field_ids:
            _list.append({
                'field': i.field_id.name,
                'type': i.field_type,
                'not_id': i.not_id,
                'custom': i.custom,
                'model': i.field_id.relation
            })

        # 校验内容是否为空
        if not _list:
            raise UserError('导入配置为空')
        # excel文件属性
        model_name = self.model_id.model_id.model
        xlsx = xlrd.open_workbook(file_contents=base64.decodebytes(self.file))
        sheet1 = xlsx.sheets()[0]
        # sheet name也就是模型名称
        excel_model_name = sheet1.name
        if excel_model_name != model_name:
            raise UserError('导入文件与导入配置模型不匹配！')
        # 开始读取导入
        for rx in range(1, sheet1.nrows):
            row = sheet1.row(rx)
            data_dict = dict()
            for rw in range(0, sheet1.ncols):
                if _list[rw].get('custom'):
                    excel_value = row[rw].value
                    # 字段对象关系
                    model = _list[rw].get('model')
                    # 自定义字段
                    _field = _list[rw].get('custom')
                    # 查询id
                    value_id = self.env[model].search([(_field, '=', excel_value)], limit=1).id
                    data_dict.update({
                        _list[rw]['field']: value_id
                    })
                else:
                    value = int(row[rw].value) if _list[rw]['type'] in ['many2one', 'one2many'] else row[rw].value
                    data_dict.update({
                        _list[rw]['field']: value
                    })
            data_list.append(data_dict)
        res = self.env[model_name].create(data_list)
        res_list = [re.id for re in res]
        _logger.info('导入成功')

        return {
            'name': "导入结果",
            'view_mode': 'tree,form',
            'res_model': model_name,
            'view_id': False,
            'type': 'ir.actions.act_window',
            'domain': [('id', 'in', res_list)]
        }
